package dao

import (
	"github.com/pkg/errors"
	"nft-server/model"
)

type AssetRelationDao struct {
	BaseDao
}

type IAssetRelationDao interface {
	GetAssetOwner(collectionIndex, tokenId string) (*model.AssetRelation, error)
	GetAssetRelationByCollectionId(collectionIndex string, userId int, subCollectionIndex int) ([]*model.AssetRelation, error)
	UpdateAssetRelation(assetRelation *model.AssetRelation) error
	DeleteAssetRelation(collectionIndex, tokenId string, userId int) error
	InsertMultiAssetRelation(assetRelations []*model.AssetRelation) (int64, error)
}

func GetAssetRelationDao() IAssetRelationDao {
	dao := &AssetRelationDao{}
	dao.Init()
	return dao
}
func (ard *AssetRelationDao) InsertMultiAssetRelation(assetRelations []*model.AssetRelation) (int64, error) {
	nums, err := ard.O.InsertMulti(len(assetRelations), assetRelations)
	return nums, err
}
func (ard *AssetRelationDao) GetAssetOwner(collectionIndex, tokenId string) (*model.AssetRelation, error) {
	assetRelation := model.AssetRelation{}
	err := ard.O.QueryTable(&model.AssetRelation{}).Filter("collection_index", collectionIndex).Filter("token_id", tokenId).One(&assetRelation)
	if err != nil {
		return nil, errors.Errorf("read error: %v", err)
	}
	return &assetRelation, nil
}
func (ard *AssetRelationDao) GetAssetRelationByCollectionId(collectionIndex string, userId int, subCollectionIndex int) ([]*model.AssetRelation, error) {
	var assetRelations []*model.AssetRelation
	_, err := ard.O.QueryTable(&model.AssetRelation{}).Filter("user_id", userId).Filter("collection_index", collectionIndex).Filter("sub_collection_index", subCollectionIndex).All(&assetRelations)
	if err != nil {
		return nil, errors.Errorf("query table error: %v", err)
	}
	return assetRelations, nil
}
func (ard *AssetRelationDao) UpdateAssetRelation(assetRelation *model.AssetRelation) error {
	_, err := ard.O.Update(assetRelation)
	if err != nil {
		return errors.Errorf("update error: %v", err)
	}
	return nil
}
func (ard *AssetRelationDao) DeleteAssetRelation(collectionIndex, tokenId string, userId int) error {
	assetRelation := new(model.AssetRelation)
	assetRelation.CollectionIndex = collectionIndex
	assetRelation.TokenId = tokenId
	assetRelation.UserId = userId
	_, err := ard.O.Delete(assetRelation, "collection_index", "token_id", "user_id")
	if err != nil {
		return errors.Errorf("delete error: %v", err)
	}
	return nil
}
